﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZMCA.UI.Model;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCA.UI.Utils;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCommon;

namespace Baosight.ZNH.ZMCA.UI
{
    public partial class ZMCA21 : EFViewCmes
    {
        public ZMCA21()
        {
            InitializeComponent();
            Chart.DefaultView.ChartLegend.Header = string.Empty;
            dataPicker.SetEngineeringNameAllItem(false);
            dataPicker.SetEngineeringOrgAllItem(false);

        }

        public void OnQueryButtonClick(object sender, RoutedEventArgs e)
        {
            //summariseType：0总体趋势图，1单位对比图，2工程对比图
            string summariseType = "0";
            if (dataPicker.IsCheckedAllOrg())//选择了全部单位
            {
                if (dataPicker.GetEngineeringName().Count == 1)
                {
                    summariseType = "0";//只选择了一个工程
                }
                else if (!dataPicker.IsCheckedAllEngineering())
                {
                    summariseType = "2";//选择了多个工程
                }
            }
            else//没有选择全部单位
            {
                if (dataPicker.IsCheckedAllEngineering())//选择全部工程
                {
                    if (dataPicker.GetEngineeringOrg().Count == 1)
                    {
                        summariseType = "0";//只选择了一个单位
                    }
                    else
                    {
                        summariseType = "1";//选择了多个单位
                    }
                }
                else
                {
                    if (dataPicker.GetEngineeringName().Count == 1)
                    {
                        summariseType = "0";//只选择了一个工程
                    }
                    else if (!dataPicker.IsCheckedAllEngineering())
                    {
                        summariseType = "2";//选择了多个工程
                    }
                }
            }
            Common.ClearChart(Chart);

            switch (summariseType)
            {

                case "0" :
                    ShowTrendChart();
                    break;
                case "1" :
                    ShowDepartmentComparationChart();
                    break;
                default :
                    ShowProjectComparationChart();
                    break;
            }

            (sender as Button).IsEnabled = false;
            TempButton = sender as Button;
        }

        /// <summary>
        /// 构造统计条件
        /// 时间和工程类型是通用的条件
        /// </summary>
        /// <returns></returns>
        private EIRow initQueryRow()
        {
            IList<EIRow> selectedDepartments = dataPicker.GetEngineeringOrg();
            string departments = "''";
            foreach (var item in selectedDepartments)
            {
                departments = departments + ",'" + item["orgCode"].ToString() + "'";
            }

            IList<EIRow> selectedProjects = dataPicker.GetEngineeringName();
            string projects = "''";
            foreach (var item in selectedProjects)
            {
                projects = projects + ",'" + item["fdKeyId"].ToString() + "'";
            }

            EIRow conRow = new EIRow();
            conRow.Add("fdFromYear", datePicker.FromDate.Year.ToString());
            conRow.Add("fdFromMonth", datePicker.FromDate.Month.ToString());
            conRow.Add("fdToYear", datePicker.ToDate.Year.ToString());
            conRow.Add("fdToMonth", datePicker.ToDate.Month.ToString());
            conRow.Add("projectType", GetProjectTypeName());
            conRow.Add("departments", departments);
            conRow.Add("projects", projects);
            return conRow;
        }
        
        /// <summary>
        /// 工程类型只有采煤计划，掘进计划和开拓计划3种
        /// </summary>
        /// <returns></returns>
        private string GetProjectTypeName()
        {
            string projectType = dataPicker.GetEngineeringType();

            switch (projectType)
            {
                case "0":
                    return "采煤计划";
                case "1":
                    return "掘进计划";
                case "3":
                    return "掘进计划";
                case "2":
                    return "钻孔计划";
                default:
                    return "采煤计划";
            }
        }

        private void ShowProjectComparationChart()
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA21");
            eiInfo.Set("method", "queryByProject");

            EIBlock conBlock = eiInfo.AddBlock("inqu_status");
            Common.AddEIColumnsToEIBlock(conBlock, new string[] { "fdToYear", "fdToMonth", "fdFromYear", "fdFromMonth", 
                "projectType", "departments", "projects" });
            EIRow conRow = initQueryRow();
            conBlock.AddRow(conRow);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, queryByProjectCompleted);
        }

        private void queryByProjectCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            ShowComparationChart(e.EIInfo, "fdProjectName");
        }

        private void ShowComparationChart(EIInfo eiInfo, string columnName)
        {
            EIBlock resultBlock = eiInfo.GetBlock("result");
            if (resultBlock.Rows.Count <= 0)
            {
                Common.Alert("没有找到数据");
                base.TempButtonOpen(true);
                return;
            }

            Chart.DefaultView.ChartTitle.Content = "对比分析";
            Chart.DefaultSeriesDefinition.ShowItemToolTips = true;
            Chart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

            SetChartDefaultLegend();

            Chart.DefaultView.ChartArea.AdditionalYAxes.Clear();

            Chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.DefaultLabelFormat = Common.ChartDefaultLabelFormat;

            Chart.SeriesMappings.Clear();
            SeriesMapping sm1 =  Common.AddBarToChart("计划产量", 0);
            SeriesMapping sm2 =  Common.AddBarToChart("实际产量", 1);
            sm1.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            sm2.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            Chart.SeriesMappings.Add(sm1);
            Chart.SeriesMappings.Add(sm2);

            List<List<ChartData>> itemsSource = new List<List<ChartData>>();
            List<ChartData> lstPlan = new List<ChartData>();
            List<ChartData> lstActual = new List<ChartData>();

            foreach (var item in resultBlock.Rows)
            {
                if (item[columnName].ToString().Trim() == string.Empty)
                {
                    continue;
                }
                ChartData cdPlan = new ChartData(item[columnName].ToString(), Common.GetDecimalValue(item["fdPlanMine"]));
                ChartData cdActual = new ChartData(item[columnName].ToString(), Common.GetDecimalValue(item["fdActualSum"]));

                lstPlan.Add(cdPlan);
                lstActual.Add(cdActual);
            }


            itemsSource.Add(lstPlan);
            itemsSource.Add(lstActual);

            Chart.ItemsSource = itemsSource;
            base.TempButtonOpen(true);
        }


        private void SetChartDefaultLegend()
        {
            string projectType = dataPicker.GetEngineeringType();
            if (projectType.Equals("0"))
            {
                Chart.DefaultView.ChartLegend.Header = "单位：吨";
            }
            //if (projectType.Equals("2"))
            //{
            //    Chart.DefaultView.ChartLegend.Header = "单位：米";
            //}
            else
            {
                Chart.DefaultView.ChartLegend.Header = "单位：米";
            }
        }

        private void ShowDepartmentComparationChart()
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA21");
            eiInfo.Set("method", "queryByDepartment");

            EIBlock conBlock = eiInfo.AddBlock("inqu_status");
            Common.AddEIColumnsToEIBlock(conBlock, new string[] { "fdToYear", "fdToMonth", "fdFromYear", "fdFromMonth", 
                "projectType", "departments", "projects" });
            EIRow conRow = initQueryRow();
            conBlock.AddRow(conRow);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, queryByDepartmentCompleted);
        }

        private void queryByDepartmentCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIBlock conBlock = e.EIInfo.GetBlock("inqu_status");
            string departments = conBlock.GetRow(0)["departments"].ToString() ;


            EIBlock resultBlock = e.EIInfo.GetBlock("result");
            IList<EIRow> lstOriginal = new List<EIRow>();     //一份原始的eirow的拷贝，用于累计运算
            //
            foreach (var item in resultBlock.Rows)
            {
                lstOriginal.Add(GetCloneRow(item));
            }

            foreach (var item in lstOriginal)
            {
                if (Common.GetIntValue(item["fdDepartmentLevel"]) == 1)
                    AddUpToBase(item, lstOriginal);
            }

            resultBlock.Rows.Clear();
            IList<EIRow> lstResult = new List<EIRow>();     //汇总之后的结果
            //去除用户没有选择的单位
            foreach (var item in lstOriginal)
            {
                if (departments.IndexOf(",'" + item["fdDepartmentId"] + "'") >= 0)
                {
                    lstResult.Add(item);
                }
            }

            resultBlock.AddRows(lstResult);
            ShowComparationChart(e.EIInfo, "fdDepartmentName");
        }

        private EIRow GetCloneRow(EIRow row)
        {
            return Common.CloneRow(row, 
                new string[] { "fdPlanMine", "fdActualSum", "fdDepartmentId", "fdDepartmentName", "fdParentDepartmentId" });
        }



        /// <summary>
        /// 累加函数(递归调用)
        /// </summary>
        /// <param name="item"></param>
        /// <param name="lstOriginal"></param>
        private void AddUpToBase(EIRow item, IList<EIRow> lstOriginal)
        {
            string fdDepartmentId = item["fdDepartmentId"].ToString().Trim();
            var childItems = (from element in lstOriginal
                              where (element["fdParentDepartmentId"] != null) &&
                                  (element["fdParentDepartmentId"].ToString().Trim().Equals(fdDepartmentId))
                              select element).ToList<EIRow>();

            foreach (var it in childItems)
            {
                AddUpToBase(it, lstOriginal);

                double planValue = Common.GetDoubleValue(item["fdPlanMine"]);
                double actualValue = Common.GetDoubleValue(item["fdActualSum"]);
                double pValue = Common.GetDoubleValue(it["fdPlanMine"]);
                double aValue = Common.GetDoubleValue(it["fdActualSum"]);

                item.Add("fdPlanMine", planValue + pValue);
                item.Add("acutalPrice", actualValue + aValue);
            }
        }

        private void ShowTrendChart()
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA21");
            eiInfo.Set("method", "queryByTrend");

            EIBlock conBlock = eiInfo.AddBlock("inqu_status");
            Common.AddEIColumnsToEIBlock(conBlock, new string[] { "fdToYear", "fdToMonth", "fdFromYear", "fdFromMonth", 
                "projectType", "departments", "projects" });
            EIRow conRow = initQueryRow();
            conBlock.AddRow(conRow);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, queryByTrendCompleted);
        }



        private void queryByTrendCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo eiInfo = e.EIInfo;
            EIBlock resultBlock = eiInfo.GetBlock("result");
            if (resultBlock.Rows.Count <= 0)
            {
                Common.Alert("没有找到数据");
                base.TempButtonOpen(true);
                return;
            }

            EIRow row = eiInfo.GetBlock("inqu_status").GetRow(0);
            int fdFromYear = Common.GetIntValue(row["fdFromYear"]);
            int fdFromMonth = Common.GetIntValue(row["fdFromMonth"]);
            int fdToYear = Common.GetIntValue(row["fdToYear"]);
            int fdToMonth = Common.GetIntValue(row["fdToMonth"]);

            Chart.DefaultSeriesDefinition.ShowItemToolTips = true;
            Chart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            SetChartDefaultLegend();

            Chart.DefaultView.ChartArea.AdditionalYAxes.Clear();

            Chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;
            Chart.DefaultView.ChartArea.AxisY.DefaultLabelFormat = Common.ChartDefaultLabelFormat;

            Chart.SeriesMappings.Clear();
            SeriesMapping sm1 = Common.AddBarToChart("计划产量", 0);
            SeriesMapping sm2 = Common.AddBarToChart("实际产量", 1);
            sm1.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            sm2.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            Chart.SeriesMappings.Add(sm1);
            Chart.SeriesMappings.Add(sm2);

            StackPanel spLegendHeader = new StackPanel();
            spLegendHeader.Orientation = Orientation.Horizontal;
            TextBlock tbLegendHeader = new TextBlock();
            tbLegendHeader.Text = "趋势分析";
            tbLegendHeader.Foreground = new SolidColorBrush(Colors.White);
            spLegendHeader.Children.Add(tbLegendHeader);

            //使tbLegendHeader.Text位于正中央
            TextBlock tbForAlignment = new TextBlock();
            tbForAlignment.Width = 120;
            spLegendHeader.Children.Insert(0, tbForAlignment);

            TextBlock tbEmpty = new TextBlock();
            tbEmpty.Width = 20;
            spLegendHeader.Children.Add(tbEmpty);
            //加一个勾选框用于控制趋势线的显示
            EFCheckBox cbShowLineSerie = new EFCheckBox();
            cbShowLineSerie.Content = "显示趋势线";
            cbShowLineSerie.Width = 100.0;
            cbShowLineSerie.Foreground = new SolidColorBrush(Colors.White);
            cbShowLineSerie.Checked += new RoutedEventHandler(cbShowLineSerie_Checked);
            cbShowLineSerie.Unchecked += new RoutedEventHandler(cbShowLineSerie_Unchecked);
            spLegendHeader.Children.Add(cbShowLineSerie);
            Chart.DefaultView.ChartTitle.Content = spLegendHeader;

            List<List<ChartData>> itemsSource = new List<List<ChartData>>();
            List<ChartData> lstPlan = new List<ChartData>();
            List<ChartData> lstActual = new List<ChartData>();
            List<ChartData> lstRate = new List<ChartData>();

            //使用Dictionary帮助后面填充值
            Dictionary<string, ChartData> dicPlan = new Dictionary<string, ChartData>();
            Dictionary<string, ChartData> dicActual = new Dictionary<string, ChartData>();

            //构造年月横坐标
            for (int y = fdFromYear, m = fdFromMonth; y < fdToYear || ( y == fdToYear && m <= fdToMonth); )
            {
                ChartData cdPlan = new ChartData(y + "-" + m, 0);
                ChartData cdActual = new ChartData(y + "-" + m, 0);
                lstPlan.Add(cdPlan);
                lstActual.Add(cdActual);
                lstRate.Add(new ChartData(y + "-" + m, 0));
                dicPlan.Add(cdPlan.Date, cdPlan);
                dicActual.Add(cdActual.Date, cdActual);
                m++;
                if (m == 13)
                {
                    y++;
                    m = 1;
                }
            }


            foreach (var item in resultBlock.Rows)
            {
                if (item["fdPlanYear"].ToString().Trim() == string.Empty)
                {
                    continue;
                }
                int year = Common.GetIntValue(item["fdPlanYear"]);
                int month = Common.GetIntValue(item["fdPlanMonth"]);
                string date = year + "-" + month;

                dicPlan[date].DataValue = Common.GetDecimalValue(item["fdPlanMine"]);
                dicActual[date].DataValue = Common.GetDecimalValue(item["fdActualSum"]);
            }

            for (int i = 0; i < lstRate.Count; i++)
            {
                lstRate[i].DataValue = Common.GetPercent(lstActual[i].DataValue, lstPlan[i].DataValue);
            }

            itemsSource.Add(lstPlan);
            itemsSource.Add(lstActual);
            itemsSource.Add(lstRate);

            Chart.ItemsSource = itemsSource;
            base.TempButtonOpen(true);
        }

        void cbShowLineSerie_Unchecked(object sender, RoutedEventArgs e)
        {
            Chart.DefaultView.ChartArea.AdditionalYAxes.Clear();
            Chart.SeriesMappings.RemoveAt(Chart.SeriesMappings.Count - 1);
        }

        private void ShowLineSerie()
        {
            Chart.DefaultView.ChartArea.AdditionalYAxes.Clear();
            Chart.DefaultView.ChartArea.AdditionalYAxes.Add(new AxisY());
            Chart.DefaultView.ChartArea.AdditionalYAxes[0].AxisName = "Secondary";
            Chart.DefaultView.ChartArea.AdditionalYAxes[0].Title = "完成率";
            Chart.DefaultView.ChartArea.AdditionalYAxes[0].DefaultLabelFormat = "P";

            SeriesMapping sm3 = Common.AddPercentageSplineToChart("完成率", 2);
            Chart.SeriesMappings.Add(sm3);
        }

        void cbShowLineSerie_Checked(object sender, RoutedEventArgs e)
        {
            ShowLineSerie();
        }




        private static void AddSplineSeriesMapping(RadChart chart, string legendLabel, int index, string axisName)
        {
            SeriesMapping sm5 = new SeriesMapping();
            SplineSeriesDefinition d5 = new SplineSeriesDefinition();
            d5.AxisName = axisName;
            sm5.SeriesDefinition = d5;
            sm5.LegendLabel = legendLabel;
            sm5.CollectionIndex = index;
            sm5.SeriesDefinition.ShowItemLabels = false;
            sm5.SeriesDefinition.ShowItemToolTips = true;
            sm5.SeriesDefinition.ShowZeroValuesLabels = true;
            sm5.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            sm5.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            sm5.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            sm5.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            sm5.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            sm5.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            chart.SeriesMappings.Add(sm5);
        }

        private static void AddSeriesMapping(RadChart chart, string legendLabel,int index)
        {
            SeriesMapping sm1 = new SeriesMapping();
            BarSeriesDefinition d1 = new BarSeriesDefinition();
            sm1.SeriesDefinition = d1;
            sm1.LegendLabel = legendLabel;
            sm1.CollectionIndex = index;
            sm1.SeriesDefinition.ShowItemLabels = false;
            sm1.SeriesDefinition.ShowItemToolTips = true;
            sm1.SeriesDefinition.ShowZeroValuesLabels = true;
            sm1.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            sm1.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            sm1.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            sm1.SeriesDefinition.ItemLabelFormat = Common.ChartItemLabelFormat;
            chart.SeriesMappings.Add(sm1);
        }
    }
}
